//
// Created by yangchao on 2022/5/15.
// 94. 二叉树的中序遍历: https://leetcode.cn/problems/binary-tree-inorder-traversal/
//

#include "../DataStructure/TreeNode.h"
#include <vector>
#include <stack>
using namespace std;

class InorderTraversal{
public:
    //递归
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inorder(root,res);
        return res;
    }

    //迭代
    vector<int> inorderTraversal2(TreeNode* root) {
        stack<TreeNode*> stk;
        vector<int> res;
        TreeNode* node = root;
        while (node != nullptr || !stk.empty()) {
            while (node != nullptr) {
                stk.push(node);
                node = node->left;
            }
            node = stk.top();
            stk.pop();
            res.push_back(node->val);
            node = node->right;
        }
        return res;
    }

private:
    void inorder(TreeNode* root, vector<int> &res) {
        if (root == nullptr) return;
        inorder(root->left,res);
        res.push_back(root->val);
        inorder(root->right,res);
    }
};

